<template>
	<div>
		<h1>录制视频</h1>
		<video ref="videoElement" autoplay muted></video>
		<div>
			<button @click="startRecording">开始录制</button>
			<button @click="stopRecording" :disabled="!isRecording">停止录制</button>
			<button @click="uploadVideo" :disabled="!videoBlob">上传视频</button>
		</div>
	</div>
</template>

<script>
import { ref, onMounted } from 'vue';

export default {
	setup() {
		const videoElement = ref(null);
		const mediaRecorder = ref(null);
		const videoBlob = ref(null);
		const isRecording = ref(false);

		const startRecording = async () => {
			try {
				// 获取视频和音频流
				const stream = await navigator.mediaDevices.getUserMedia({
					video: true,
					audio: true
				});

				videoElement.value.srcObject = stream;

				// 创建 MediaRecorder 实例进行录制
				mediaRecorder.value = new MediaRecorder(stream);

				let chunks = [];

				mediaRecorder.value.ondataavailable = (event) => {
					chunks.push(event.data);
				};

				mediaRecorder.value.onstop = () => {
					videoBlob.value = new Blob(chunks, { type: 'video/webm' });
					chunks = [];
				};

				mediaRecorder.value.start();
				isRecording.value = true;
			} catch (err) {
				console.error('无法访问摄像头和麦克风:', err);
			}
		};

		const stopRecording = () => {
			if (mediaRecorder.value && isRecording.value) {
				mediaRecorder.value.stop();
				isRecording.value = false;
			}
		};

		const uploadVideo = async () => {
			if (!videoBlob.value) return;

			const formData = new FormData();
			formData.append('video', videoBlob.value, 'video.webm');

			try {
				const response = await fetch('http://localhost:4000/index/luzhi_video_post', {
					method: 'POST',
					body: formData
				});

				if (response.ok) {
					console.log('视频上传成功');
				} else {
					console.log('视频上传失败');
				}
			} catch (error) {
				console.error('上传视频失败:', error);
			}
		};

		return {
			videoElement,
			startRecording,
			stopRecording,
			uploadVideo,
			isRecording,
			videoBlob
		};
	}
};
</script>

<style scoped>
video {
	width: 100%;
	max-width: 600px;
	margin: 10px 0;
}
button {
	margin: 5px;
}
</style>
